package com.neusoft.EYSystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neusoft.EYSystem.dao.*;
import com.neusoft.EYSystem.po.*;
import com.neusoft.EYSystem.service.CheckinRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CheckinRecordServiceImpl implements CheckinRecordService {
    @Autowired
    private CheckinRecordDAO checkinRecordDAO;

    @Autowired
    private ClientDAO clientDAO;

    @Autowired
    private BedUsageDAO bedUsageDAO;


//    @Override
//    public PageResponseBean<List<ClientCheckinRecord>> checkinPage(String name, String checkinDateStart, String checkinDateEnd, String status, Long page, Long size) {
//        PageResponseBean<List<ClientCheckinRecord>> responseBean = new PageResponseBean<>();
//        QueryWrapper<CheckinRecord> queryWrapper = new QueryWrapper<>();
//        QueryWrapper<Client> clientQueryWrapper = new QueryWrapper<>();
//        clientQueryWrapper.like("name", name);
//        clientDAO.selectList(clientQueryWrapper).forEach(client -> {
//            queryWrapper.eq("client_id", client.getClientId()).eq("status", status);
//            //设计between
//
//            List<CheckinRecord> checkinRecords = checkinRecordDAO.selectPage(queryWrapper, page, size).getRecords();
//            if (!checkinRecords.isEmpty()) {
//                ClientCheckinRecord clientCheckinRecords = new ClientCheckinRecord();
//                clientCheckinRecords.setClient(client);
//                clientCheckinRecords.setCheckinRecord(checkinRecords);
//            }
//        });
//
//
//        return responseBean;
//    }

    @Override
    public PageResponseBean<List<ClientCheckinRecord>> checkinPage(String name, String checkinDateStart, String checkinDateEnd, String status, Long page, Long size) {
        PageResponseBean<List<ClientCheckinRecord>> responseBean = new PageResponseBean<>();

        // 1. 先查出所有匹配名字的ClientId
        List<Long> clientIds;
        QueryWrapper<Client> clientQueryWrapper = new QueryWrapper<>();
        if (name != null && !name.isEmpty()) {
            clientQueryWrapper.like("name", name);
        }else{
            clientQueryWrapper.isNotNull("name"); // 如果没有提供名字，则查询所有客户
        }
        if(status != null && !status.isEmpty()){
            if("自理老人".equals(status)) {
                clientQueryWrapper.isNull("user_id"); // 自理老人没有健康管家
            }
            else if("护理老人".equals(status)) {
                clientQueryWrapper.isNotNull("user_id"); // 护理老人有健康管家
            }
        }

        clientIds = clientDAO.selectList(clientQueryWrapper)
                .stream()
                .map(Client::getClientId)
                .map(Integer::longValue)
                .collect(Collectors.toList());

        if (clientIds.isEmpty()) {
            // 没有匹配直接返回空页
            responseBean.setData(Collections.emptyList());
            responseBean.setTotal(0);
            responseBean.setStatus(200);
            responseBean.setMsg("没有匹配的老人");
            return responseBean;
        }

        // 2. 构建入住记录的查询
        QueryWrapper<CheckinRecord> queryWrapper = new QueryWrapper<>();
        if (clientIds != null && !clientIds.isEmpty()) queryWrapper.in("client_id", clientIds);
        if (checkinDateStart.isEmpty() && !checkinDateStart.isEmpty() && !checkinDateEnd.isEmpty() && checkinDateEnd != null) {
            queryWrapper.between("checkin_date", checkinDateStart, checkinDateEnd);
        } else if (checkinDateStart != null && !checkinDateStart.isEmpty()) {
            queryWrapper.ge("checkin_date", checkinDateStart);
        } else if (checkinDateEnd != null && !checkinDateEnd.isEmpty()) {
            queryWrapper.le("checkin_date", checkinDateEnd);
        }
        queryWrapper.eq("is_visible", true); // 只查询可见的入住记录
        queryWrapper.orderByDesc("checkout_date"); // 按入住日期降序排列
        // 3. 分页查入住记录
        IPage<CheckinRecord> checkinPage = new Page<>(page, size);
        IPage<CheckinRecord> checkinRecords = checkinRecordDAO.selectPage(checkinPage, queryWrapper);

        // 4. 一次性查出涉及到的Client
        Set<Long> resultClientIds = checkinRecords.getRecords().stream()
                .map(r -> r.getClientId().longValue()).collect(Collectors.toSet());
        Map<Long, Client> clientMap = new HashMap<>();
        if (!resultClientIds.isEmpty()) {
            QueryWrapper<Client> clientWrapper = new QueryWrapper<>();
            clientWrapper.in("client_id", resultClientIds);
            clientMap = clientDAO.selectList(clientWrapper)
                    .stream().collect(Collectors.toMap(c -> c.getClientId().longValue(), c -> c));
        }else{
            return new PageResponseBean<>(500, "没有找到符合条件的客户");
        }

        // 5. 组装结果
        List<ClientCheckinRecord> result = new ArrayList<>();
        for (CheckinRecord record : checkinRecords.getRecords()) {
            ClientCheckinRecord ccr = new ClientCheckinRecord();
            ccr.setClient(clientMap.get(record.getClientId().longValue()));
            ccr.setCheckinRecord(record);
            result.add(ccr);
        }

        // 6. 封装分页对象
        responseBean.setData(result);
        responseBean.setTotal(checkinRecords.getTotal());
        responseBean.setStatus(200);
        responseBean.setMsg("查询成功");

        return responseBean;
    }

    @Override
    public ResponseBean<Integer> deleteCheckinRecordLogic(Integer recordId) {
        ResponseBean<Integer> responseBean = new ResponseBean<>();
        CheckinRecord checkinRecord = checkinRecordDAO.selectById(recordId);
        if (checkinRecord == null) {
            responseBean.setStatus(404);
            responseBean.setMsg("入住记录不存在");
            return responseBean;
        }

        // 逻辑删除
        checkinRecord.setIsVisible(false);
        int rowsAffected = checkinRecordDAO.updateById(checkinRecord);
        if (rowsAffected > 0) {
            responseBean.setStatus(200);
            responseBean.setMsg("入住记录删除成功");
            responseBean.setData(rowsAffected);
        } else {
            responseBean.setStatus(500);
            responseBean.setMsg("入住记录删除失败");
        }
        return responseBean;
    }

    @Transactional
    @Override
    public ResponseBean<Integer> updateCheckinRecordEndDate(Client client) {
        ResponseBean<Integer> response = new ResponseBean<>();
        QueryWrapper<CheckinRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("client_id", client.getClientId())
                .eq("is_visible", true);
        CheckinRecord checkinRecord = checkinRecordDAO.selectOne(queryWrapper);
        Client existingClient = clientDAO.selectById(client.getClientId());
        QueryWrapper<BedUsage> bedUsageQueryWrapper = new QueryWrapper<>();
        bedUsageQueryWrapper.eq("client_id", client.getClientId())
                .eq("status", "使用中")
                .eq("bed_id", existingClient.getBedId());
        BedUsage bedUsages = bedUsageDAO.selectOne(bedUsageQueryWrapper);

        checkinRecord.setCheckoutDate(client.getContractEndDate());
        existingClient.setContractEndDate(client.getContractEndDate());
        bedUsages.setEndDate(client.getContractEndDate());

        int checkinUpdate = checkinRecordDAO.updateById(checkinRecord);
        int clientUpdate = clientDAO.updateById(existingClient);
        int bedUsageUpdate = bedUsageDAO.updateById(bedUsages);

        if (checkinUpdate > 0 && clientUpdate > 0 && bedUsageUpdate > 0) {
            response.setStatus(200);
            response.setMsg("入住记录结束日期更新成功");
            response.setData(checkinUpdate);
        } else {
            response.setStatus(500);
            response.setMsg("入住记录结束日期更新失败");
        }
        return response;
    }


}
